package com.zyh.controller;

import com.zyh.service.OrderService;
import com.zyh.util.AlipayTemplate;
import com.zyh.util.PayVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Controller
@RequestMapping("/ali")
public class PayController {
    @Autowired
    private ModelAndView mav;
    @Autowired
    private OrderService orderService;
    @Autowired
    private AlipayTemplate alipayTemplate;

    @RequestMapping("/pay")
    public void pay(HttpServletResponse response,String orderId,String amount) throws Exception{
        //设置响应头格式
        response.setContentType("text/html;charset=UTF-8");

        PayVo payVo = new PayVo();
        payVo.setOut_trade_no(orderId);
        payVo.setTotal_amount(amount);
        payVo.setBody("当当网支付");
        payVo.setSubject("图书");
        //发送支付请求
        String pay = alipayTemplate.pay(payVo);

        PrintWriter writer = response.getWriter();
        writer.println(pay);
    }

    @RequestMapping("/orderPayed")
    public ModelAndView orderPayed(Integer out_trade_no, HttpServletRequest request) {
        boolean boo = alipayTemplate.rsaCheckV1(request);
        if(boo){
            orderService.orderPayed(out_trade_no);
            mav.setViewName("/order/selectByUserId.do");
        }else{
            mav.setViewName("/order/selectByUserId.do");
        }

        return mav;
    }
}
